package com.darker.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.darker.reggie.common.BaseContext;
import com.darker.reggie.common.R;
import com.darker.reggie.entity.AddressBook;
import com.darker.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    AddressBookService addressBookService;
    //添加地址
    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookService.save(addressBook);
        return R.success("保存成功");
    }

    @GetMapping("/list")
    public R<List<AddressBook>> list() {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        List<AddressBook> list = addressBookService.list(queryWrapper);
        return R.success(list);
    }
    //修改默认地址
    @PutMapping("/default")
    public R<String> isDefault(@RequestBody AddressBook addressBook) {
        //找到isDefault字段为1的值设置为0
        Long id = addressBook.getId();
        LambdaUpdateWrapper<AddressBook> UpdateWrapper = new LambdaUpdateWrapper<>();
        UpdateWrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        UpdateWrapper.set(AddressBook::getIsDefault, 0);
        addressBookService.update(UpdateWrapper);
        //设置默认地址
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);

        return R.success("设置成功");
    }
    @GetMapping("/{id}")
    public R<AddressBook> getById(@PathVariable Long id){
        AddressBook addressBook = addressBookService.getById(id);
        return R.success(addressBook);
    }
    //修改地址
    @PutMapping
    public R<String> updateById(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);
        return R.success("修改成功");
    }
    //删除地址
    @DeleteMapping
    public R<String> delById(long ids){
        addressBookService.removeById(ids);
        return R.success("删除成功");
    }
    //获取默认地址
    @GetMapping("/default")
    public R<AddressBook> getone(){
        LambdaQueryWrapper<AddressBook> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId,BaseContext.getCurrentId())
                .eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(queryWrapper);
        return R.success(addressBook);
    }

}
